//
//  RequestApi.swift
//
//
//  Created by 李仁博 on 2025/4/28.
//

import Alamofire
import Foundation

public enum ServerError: Error {
    case invalidParameter

    case parsingFailure

    case customError(code: Int, message: String)
}

class RequestApi: Request {
    // 自定义error code，并使用LNRequestFailure返回
    var errorCode: Int = 0
    var responseData: Any?

    // 自定义统一处理响应结果
    override func process(showToast: Bool = true, isReturnAll: Bool, delegate: AnyObject?, response: AFDataResponse<Data?>, success: RequestSuccess?, failure: RequestFailure? = nil) {
        RequestApi.endRefresh(delegate)
        switch response.result {
        case let .success(data):
            guard let sourceData = data else { return }
            do {
                let jsonData = try JSONSerialization.jsonObject(with: sourceData, options: .allowFragments)

                let result = jsonData as? [String: Any]
                if (result?.keys.contains(RESPONSE_CODE)) == nil {
                    success?(self, jsonData)
                } else {
                    let codeStr = "\((jsonData as! [String: Any])[RESPONSE_CODE]!)"
                    let code = Int(codeStr)
                    let msgStr = "\((jsonData as! [String: Any])[RESPONSE_MESSAGE]!)"

                    if code == RESPONSE_CODE_SUCCESS {
                        // success
                        // let result = jsonData as? [String: Any]
                        let resp = BaseRespModel.deserialize(from: result)
                        success?(self, isReturnAll ? resp as Any : resp?.excepting as Any)
                    } else if code == RESPONSE_CODE_LOGINFAILURE {
                        // 登录失效 - 重新登录
                        GlobalMethod.showAlert(strAlert: "登录失效")
                        GlobalMethod.relogin()
                        return
                    } else {
                        if showToast == true {
                            if url.absoluteString.contains(ApiConfig.getLoginCode) {
                                GlobalMethod.showAlert(strAlert: msgStr, time: 3)
                            } else {
                                GlobalMethod.showAlert(strAlert: msgStr)
                            }
                        }
                        failure?(self, ServerError.customError(code: code!, message: msgStr))
                    }
                }
            } catch {
                let error = AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))
                failure?(self, error)
            }
        case let .failure(error):
            failure?(self, error)
        }
    }

    override func processDownload(response: AFDownloadResponse<URL?>, success: RequestSuccess?, failure: RequestFailure? = nil) {
        switch response.result {
        case let .success(data):
            success?(self, data?.absoluteString as Any)
        case let .failure(error):
            failure?(self, error)
        }
    }

    // 结束刷新
    static func endRefresh(_ delegate: AnyObject?) {
        let selector = #selector(BaseTableVC.endRefreshing)
        if let delegate = delegate as? BaseTableVC, delegate.responds(to: selector) {
            delegate.perform(selector)
        }
    }
}
